
*-------------------------------------------------------------------------------
* Estimate bias-corrected rents and cd's for grand means across windows
* Make make sure to run "07_split_sample_check_3stack" first!
*-------------------------------------------------------------------------------

cap log close
log using "$log/15_02_split_sample_check_3stack_grand_${S_DATE}", text replace


*-----------------------------------
*Compute the bias-corrected slopes
*-----------------------------------

use $temp/firmfe_value_split_all3stack, clear

*Residualized variables
forvalues s = 1/2{
	reghdfe firm_fe`s' [aweight = av_worker_years], a(window) resid(firm_fe`s'_R)
	reghdfe value`s' [aweight = av_worker_years], a(window) resid(value`s'_R)
}
reghdfe firm_fe [aweight = av_worker_years], a(window) resid(firm_fe_R)
reghdfe value [aweight = av_worker_years], a(window) resid(value_R)

collapse (mean) *_R av_worker_years, by(betnr)
rename firm_fe1_R firm_fe1
rename value1_R value1
rename firm_fe2_R firm_fe2
rename value2_R value2
rename firm_fe_R firm_fe
rename value_R value

*Bias-correction of residualized variables
gen rent_bc = .
gen cd_bc   = .
 
ivregress 2sls firm_fe1 (value1=value2) [aweight = av_worker_years]
replace rent_bc = _b[value1]*value + _b[_cons]
replace cd_bc   = firm_fe - rent_bc

* Output data
keep betnr firm_fe rent_bc cd_bc
rename rent_bc rents
rename cd_bc cd
save "$temp/firmfe_value_new_3stack_grand_bc.dta", replace

* insure same sample as 3-stack
forval t = 1999(3)2017 {	
	use "$temp/firmfe_value_new_3stack_grand_bc.dta", clear
	merge 1:1 betnr using "$temp/firmfe_value_new_ver`t'3_bc.dta", keep(3) keepusing(betnr) nogen
	save "$temp/firmfe_value_new_ver`t'3_grand_bc.dta", replace
}	


*Merge the split-sample variables for each window
local i_list = "19993 20023 20053 20083 20113 20143 20173" 

foreach i in `i_list' {
	dis "`i_list'"
	
	use "$temp/firmfe_value_new_ver`i'_grand_bc.dta", clear
	
	rename rents rent_bc_grand
	rename cd cd_bc_grand
	rename firm_fe firm_fe_grand
	
	merge 1:1 betnr using "$temp/firmfe_value_new_ver`i'_bc.dta", assert(3)
	drop _merge
	replace firm_fe = firm_fe - firm_fe_grand
	replace rents = rents - rent_bc_grand
	replace cd = cd - cd_bc_grand
	drop *_grand
	save "$temp/firmfe_value_new_grand_resid_ver`i'_bc.dta", replace
	
}
	

clear
log close	
		
